import React, { useEffect, useState} from "react";
import { Button, Table } from "antd";
import axios from "axios";
export default function UserList() {
  const [dataSource, setDataSource] = useState([]);
  // 获取登录用户信息
  const {
    region,
    role: { id },
    username
  } = JSON.parse(localStorage.getItem("token"));

  useEffect(() => {
    const getRightList = async () => {
      if (id === 1) {
        const res = await axios.get(
          `http://localhost:3000/news?_expand=category&auditState=1`
        );
        setDataSource(res.data);
      } else {
        //普通管理员 只负责自己的区域 并且不能审核自己的新闻
        const res = await axios.get(
          `http://localhost:3000/news?region=${region}&_expand=category&auditState=1&author_ne=${username}`
        );
        setDataSource(res.data);
      }
    };
    getRightList();
  }, [id,region,username])

  const columns = [
    {
      title: "新闻标题",
      dataIndex: "title",
      render:(title,item)=>{
        return <a href={`#/news-manage/preview/${item.id}`}>{title}</a>
      }
    },
    {
      title: "作者",
      dataIndex: "author",
    },
    {
      title: "新闻分类",
      dataIndex: "category",
      key: "category",
      render: (category) => {
        return <div>{category.title}</div>;
      },
    },
    {
      title: "操作",
      render: (item) => {
        return (
          <>
            <Button
              onClick={()=>{
                setDataSource(dataSource.filter((data) => data.id !== item.id));
                axios.patch(`http://localhost:3000/news/${item.id}`,{auditState:2,publishState:1})
              }}
            >
              通过
            </Button>
            <Button danger
              onClick={()=>{
                setDataSource(dataSource.filter((data) => data.id !== item.id));
                axios.patch(`http://localhost:3000/news/${item.id}`,{auditState:3})
              }}
            >
              驳回
            </Button>
          </>
        );
      },
    },
  ];

  return (
    <div>
      <Table
        dataSource={dataSource}
        columns={columns}
        pagination={{
          pageSize: 5,
        }}
        rowKey={(item) => item.id}
      />
    </div>
  );
}
